package com.dx.oa.sysmng.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dx.oa.framework.dto.TreeDto;
import com.dx.oa.framework.util.TreeUtil;
import com.dx.oa.framework.util.UserUtils;
import com.dx.oa.sysmng.entity.Dict;
import com.dx.oa.sysmng.entity.Area;
import com.dx.oa.sysmng.entity.User;
import com.dx.oa.sysmng.service.IAreaService;

/**
 * 部门功能的Controller
 * @author dx911
 *
 */
@Controller
@RequestMapping("/sysmgr/area")
public class AreaController {
	
	@Autowired
	private IAreaService areaService;

	private static Logger logger = Logger.getLogger(AreaController.class);

	/**
	 * 进入字典查询功能
	 * @return
	 */
	@RequestMapping("/gotoAreaList")
	public String gotoAreaList(Model model)
	{
		
		List<Area> sortAreaList = new ArrayList<Area>();
		//List<Area> areaList =  areaService.getAreaList();
		List<Area> areaList = areaService.getAreaListByUserId(UserUtils.getCurrentUserId());
		TreeUtil.sortTreeList(areaList, sortAreaList, 0);
		model.addAttribute("areaList",sortAreaList);
		
		return "sysmanage/area/areaList";
	}
	
	//进入字典编辑功能
	@RequestMapping("/gotoAreaEdit")
	public String gotoAreaEdit(@ModelAttribute("editFlag") int editFlag, Integer areaId,Integer parentId, Model model)
	{	
		if(editFlag == 2 && areaId != null)
		{
			model.addAttribute("area", areaService.getAreaById(areaId));
		}
		if(editFlag == 1 && parentId != null)
		{
			Area area = new Area();
			area.setParentId(parentId);
			area.setParentName(areaService.getAreaById(parentId).getName());
			System.out.println(area.getParentName());
			model.addAttribute("area", area);
		}
		return "sysmanage/area/areaEdit";
	}
	
	/**
	 * 对于树形结构的数据,我们在删除的时候需要注意,必须保证无子节点删除
	 * @param areaId
	 * @return
	 */

	@RequestMapping("/delArea")
	public @ResponseBody Map<String,Object> delArea(Integer areaId)
	{
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(areaService.getChildCnt(areaId) > 0)
		{
			resultMap.put("result", "请先删除该菜单下的子菜单");
			return resultMap;
		}
		try
		{
			int row = areaService.deleteAreaById(areaId);
			if(row > 0)
			{
				resultMap.put("result", "删除成功");
			}
			else
			{
				resultMap.put("result", "删除失败");
				logger.error("删除菜单失败");
			}
		}
		catch(Exception e)
		{
			resultMap.put("result", "删除失败");
			logger.error("删除菜单失败",e);
		}
		return resultMap;
	}

	/**
	 * 获取所有树形结构菜单节点信息，
	 * @param areaId
	 * @return
	 */
	@RequestMapping("/getParentAreaTreeData")
	public @ResponseBody List<TreeDto> getParentAreaTreeData(Integer areaId)
	{
		logger.info(areaId);
		//areaId = 30;

		List<TreeDto> resAreaList = new ArrayList<TreeDto>();
	
		List<Area> areaList = areaService.getAreaList();
		
		for(Area area:areaList)
		{
			resAreaList.add(area);
		}
		
		if(areaId != null)
		{
			Set<Integer> retSet = TreeUtil.getChildHashSet(resAreaList,areaId);
			List<TreeDto> retAreaList = new ArrayList<TreeDto>();
			for(TreeDto td:resAreaList)
			{
				if(!retSet.contains(td.getId()))
				{
					retAreaList.add(td);
				}
			}
			return retAreaList;
		}

		return resAreaList;
	}
	
	//保存修改
	@RequestMapping("/saveArea")
	public @ResponseBody Map<String,String> saveArea(Area area,HttpSession session,Model model)
	{
		//System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + ":");
		//System.out.println(area);
		Map<String,String> responseMap = new HashMap<String,String>();
		
		//System.out.println("mdict:"+ mdict.toString());
		
		if(area == null)
		{
			responseMap.put("result", "操作失败");
			return responseMap;
		}
		area.setDelFlag('0');
		User tuser = (User)session.getAttribute("user");
		if(tuser != null)
			area.setUpdateBy(UserUtils.getCurrentUserId().toString());
		area.setUpdateDate(new Timestamp(System.currentTimeMillis()));
		if(area.getId() == null)
		{
		//	area.setCreateBy(((User)session.getAttribute("user")).getUserNo());
		//	area.setCreateDate(new Timestamp(System.currentTimeMillis()));
			if(areaService.insertArea(area) > 0)
			{
				List<Area> areaList =  areaService.getAreaList();
				List<Area> sortAreaList = new ArrayList<Area>();
				TreeUtil.sortTreeList(areaList, sortAreaList, 0);
				model.addAttribute("areaList", sortAreaList);
				responseMap.put("result", "插入成功");
			}
			else
				responseMap.put("result", "插入失败");
		}
		else
		{
			if(areaService.updateArea(area) > 0)
			{
				List<Area> areaList =  areaService.getAreaList();
				List<Area> sortAreaList = new ArrayList<Area>();
				TreeUtil.sortTreeList(areaList, sortAreaList, 0);
				model.addAttribute("areaList", sortAreaList);
				responseMap.put("result","更新成功");
			}
			else
				responseMap.put("result", "更新失败");
		}
		return responseMap;
	}
	
}
